package main

import (
	"bytes"
	"fmt"
	"gitee.com/tietang/terrace-go/v2/lib/tollgate/handler/jvm"
	"github.com/shirou/gopsutil/v3/process"
	"os/exec"
	"strconv"
	"strings"
)

type KV struct {
	Key, Value string
}
type JvmProcess struct {
	Pid              int
	Main             string
	ServletContainer string
	ServiceId        string
	Args             map[string]KV
	Lables           []string
}

func main() {
	replacer := strings.NewReplacer("Application", "", "App", "", "Main", "", "Bootstrap", "")

	jps, err := jvm.GetJpsPath()
	cmd := exec.Command(jps, "-lvm")
	data, err := cmd.Output()
	if err != nil {
		fmt.Println(err.Error())
	}
	cmdlines := bytes.Split(data, []byte("\n"))
	JvmProcesses := make([]JvmProcess, 0)
	for _, cl := range cmdlines {
		fmt.Println(string(cl))
		cmds := bytes.Split(cl, []byte(" "))
		pid, err := strconv.Atoi(string(cmds[0]))
		if err != nil {
			continue
		}
		jp := JvmProcess{Pid: pid, Main: string(cmds[1]), Lables: make([]string, 0), Args: make(map[string]KV, 0)}
		jp.ServiceId = replacer.Replace(jp.Main)
		size := len(cmds)
		fmt.Println(size)

		for i := 2; i < size; i++ {
			c := cmds[i]
			if strings.Index(string(c), "-D") >= 0 {
				kvs := bytes.Split(c, []byte("="))
				key := kvs[0][2:]
				value := kvs[1]
				k := string(key)
				jp.Args[k] = KV{Key: k, Value: string(value)}
				if strings.ToLower(k) == "service.id" {
					jp.ServiceId = string(value)
				}
			} else {
				jp.Lables = append(jp.Lables, string(c))
			}

		}
		JvmProcesses = append(JvmProcesses, jp)
	}
	fmt.Println(JvmProcesses)

	fmt.Println(string(data))
	p, _ := process.NewProcess(4013)
	fmt.Println(p.Cmdline())
	fmt.Println(p.Connections())
	fmt.Println(p.Status())
	fmt.Println(p.IOCounters())

}
